package com.example.exam.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.exam.domain.StudentDO;
import com.example.exam.domain.vo.UserVO;
import com.example.exam.service.IStudentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
@AllArgsConstructor
public class LoginController {

    private final IStudentService studentService;

    @GetMapping({"/login","/"})
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(UserVO user, HttpSession session, Model model){
        if(StrUtil.isBlank(user.getUsername())|| StrUtil.isBlank(user.getPassword())){
            model.addAttribute("msg","账号密码不能为空！");
            return "login";
        }
        StudentDO studentDO = studentService.getOne(new LambdaQueryWrapper<StudentDO>()
                .eq(StudentDO::getPhone,user.getUsername())
                .eq(StudentDO::getPassword,user.getPassword()));
        if (BeanUtil.isNotEmpty(studentDO)) {
            session.setAttribute("loginUser",studentDO);
            return "redirect:/index.html";
        }else{
            model.addAttribute("msg","账号密码错误！");
            return "login";
        }
    }
}
